<?php

namespace App\Admin\Forms\Service;

use App\Admin\Repositories\GoodOrderDetail;
use App\Http\Library\WeChat\MiniWeChat;
use App\Models\GoodOrder;
use App\Models\OrderCommission;
use App\Models\ShopUser;
use App\Models\UserMoney;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Grid;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Exception;
use Illuminate\Database\Eloquent\ModelNotFoundException;

class HandleRefund extends Form implements LazyRenderable
{
    use LazyWidget;

    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input)
    {
         $res = 0;
         if ($input){
             try {
                 $oid = $input['oid'];
                 $order = GoodOrder::whereId($oid)->first();
                 $refund_state = $input['refund_state'];
                 if ($order->state==5){
                     throw new Exception("此订单状态已退款");
                 }
                 if (!$order->is_apply){
                     throw new Exception("不是退款申请,不可审核退款");
                 }
                 if ($refund_state==2){
                     $order->is_apply = 0;
                     $order->refund_no = null;
                 }elseif($refund_state==1){
                     $out_trade_no = $order->order_no;
                     $user_id = $order->user_id;
                     $amount = $order->amount;
                     if ($order->pay_way){
                         $money = $amount*100;
                         $refund_no = $order->refund_no;
                         $wechat = MiniWeChat::instance();
                         $result = $wechat->byOutTradeNumber($out_trade_no,$refund_no,$money,$money,[
                                 'refund_desc'=>'商品订单退款'
                         ]);
                         if ($result['return_code']==='SUCCESS'&&$result['result_code']==='SUCCESS'){
                             $order->state = 5;
                             $order->is_apply = 0;
                             $order->refund_time = now()->format("Y-m-d H:i:s");
                             OrderCommission::whereOrderId($out_trade_no)->update(['is_settle'=>2]);
                         }else{
                             $msg = $result['return_msg']?:'退款失败!';
                             $msg = $msg=='OK'?$result['err_code_des']:$msg;
                             throw new Exception($msg);
                         }
                     }else{
                         $order->state = 5;
                         $order->is_apply = 0;
                         $order->refund_time = now()->format("Y-m-d H:i:s");
                         UserMoney::money(1,$user_id,$amount,"商品订单退款");
                         OrderCommission::whereOrderId($out_trade_no)->update(['is_settle'=>2]);
                     }
                 }
                 $res = $order->save();
             }catch (ModelNotFoundException|Exception $e){
                 return $this->response()->error($e->getMessage())->refresh();
             }
         }
         return $this->response()->success($res?'保存成功.':'暂无修改.')->refresh();
    }

    /**
     * Build a form here.
     */
    public function form()
    {
        $oid = $this->payload['oid'];
        $order = GoodOrder::whereId($oid)->first();
        $this->html($this->grid($order->order_no),"订单详情");
        $this->display("amount");
        $this->display("address.name","收件人名称");
        $this->display("address.phone","收件人电话");
        $this->display("address.address","收件地址");
        $this->hidden("oid")->default($oid)->value($oid);
        $this->radio("refund_state","退款审核")->options([0=>'待审核',1=>'审核通过',2=>'审核拒绝'])->default(0);

    }

    /**
     * The data of the form.
     *
     * @return array
     */
    public function default()
    {
        return $this->getDefault();
    }

    protected function getDefault(){
        $oid = $this->payload['oid'];
        $order = GoodOrder::whereId($oid)->first();
        return $order->toArray();
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid($oid)
    {
        return Grid::make(new GoodOrderDetail(), function (Grid $grid) use ($oid) {
            $grid->disableCreateButton();
            $grid->disableColumnSelector();
            $grid->disableActions();
            $grid->disableRefreshButton();
            $grid->disableRowSelector();
            $grid->disablePagination();
            $grid->column('id')->sortable();
            $grid->model()->where("oid",$oid);
            $grid->column('good_id','商品ID');
            $grid->column('good_name','商品名称');
            $grid->column('good_image','商品图片')->image(null,40,40);
            $grid->column('good_number','商品数量');
            $grid->column('good_price','商品单价');
            $grid->column('total_price','小计');
        });
    }
}
